import pyglet
from pyglet.gl import *
import resource, fastsprite

circ32 = pyglet.graphics.vertex_list(32, ('v2f', (1,0,0.980785, 0.19509, 0.92388, 0.382683, 0.83147, 0.55557, 0.707107, 0.707107, 0.55557, 0.83147, 0.382683, 0.92388, 0.19509, 0.980785, 0, 1, -0.19509, 0.980785, -0.382683, 0.92388, -0.55557, 0.83147, -0.707107, 0.707107, -0.83147, 0.55557, -0.92388, 0.382683, -0.980785, 0.19509, -1, 0, -0.980785, -0.19509, -0.92388, -0.382683, -0.83147, -0.55557, -0.707107, -0.707107, -0.55557, -0.83147, -0.382683, -0.92388, -0.19509, -0.980785, 0, -1, 0.19509, -0.980785, 0.382683, -0.92388, 0.55557, -0.83147, 0.707107, -0.707107, 0.83147, -0.55557, 0.92388, -0.382683, 0.980785, -0.19509)))

def draw_circle(x0, y0, r):
    """Draws a circle centered at (x0, y0) with radius r."""
    glPushMatrix()
    glTranslatef(x0,y0,0)
    glScalef(r,r,0)
    if r < 40: circ16.draw(GL_LINE_LOOP)
    else: circ32.draw(GL_LINE_LOOP)
    glPopMatrix()

def draw_poly_shape(poly):
    """Draws a pymunk polygon shape attached to a body."""
    body = poly.body
    
    glBegin(GL_LINE_LOOP)
    for vert in poly.verts:
        v = body.position + poly.offset + vert.cpvrotate(body.rotation_vector)
        glVertex2f(v.x, v.y)
    glEnd()

def make_sprite(filename, anchor_x=0, anchor_y=0):
    """Silly convenience function for making a sprite."""
    image = resource.texture(filename, anchor_x, anchor_y)
    sprite = fastsprite.Sprite(image)
    return sprite

def make_animation(framelist, loops=False):
    frames = []
    for (filename, anchor_x, anchor_y, duration) in framelist:
        frame = fastsprite.SpriteFrame(resource.texture(filename, anchor_x, anchor_y), duration)
        frames.append(frame)
    if not loops:
        frames.append(0)
    return fastsprite.Sprite(frames)

######################################################################

class Rectangle(object):
    __slots__ = ['x', 'y', 'width', 'height']
    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height

    def hit(self, x, y):
        if x < self.x: return False
        if y < self.y: return False
        if x > self.x + self.width: return False
        if y > self.y + self.height: return False
        return True

    def overlaps(self, other):
        """Returns true if this rectangle intersects the other rect."""
        if self.x > other.x + other.width or self.x + self.width < other.x:
            return False
        if self.y > other.y + other.height or self.y + self.height < other.y:
            return False
        return True

    def __repr__(self):
        return '<Rectangle (%f,%f,%f,%f)>' % (self.x, self.y, self.width, self.height)

    def draw(self):
        glBegin(GL_LINE_LOOP)
        glVertex2f(self.x, self.y)
        glVertex2f(self.x+self.width, self.y)
        glVertex2f(self.x+self.width, self.y+self.height)
        glVertex2f(self.x, self.y+self.height)
        glEnd()

    
